//
//  RegisterController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/1/5.
//  Copyright © 2016年 game. All rights reserved.

#import "RegisterController.h"
#import "PersonNavView.h"
#import "OkRegister.h"
#import "AFNetworking.h"
#import "KGUserAgreementController.h"
@interface RegisterController ()
{
    UIView *_texetView;
    UITextField *_phoneNub;
    UITextField *_testText;
    UITextField *_passText;
    
    UIButton *_taseBnt;
    UILabel *_timeLab;
    NSTimer *_timer;
    BOOL isRead;
}

@property (nonatomic,copy) NSString *formhash;
@end
static int count;
@implementation RegisterController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.app.myTabBar.tabBar.hidden = YES;
        [self NavView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(242, 242, 242, 1);
    [self CrearTextField];
    [self FootView];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selfTap)];
    
    [self.view addGestureRecognizer:tap];
}
-(void)selfTap{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];

}


#pragma mark--自定义导航
-(void)NavView{

    PersonNavView *naview = [[PersonNavView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    naview.title.text = @"注册";
    naview.BackToFatherView = ^{
    if (_phoneNub.text.length==0&&_testText.text.length==0&&_passText.text.length==0) {
                     [self.navigationController popViewControllerAnimated:YES];
        }else{
        
        UIAlertController *alert = [self ShowAlertWhthTitle:@"提示" Message:@"您正在注册，离开将会放弃此次注册" CancelButtonTitle:@"取消"];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [alert addAction:cancel];
    } };
    [self.view addSubview:naview];
}
-(void)CrearTextField{

    _texetView =[self Linview:CGRectMake(-1, 84, SCREEN_WIDTH+2, screen_height*0.25) BackgroundColor:[UIColor whiteColor] AddView:self.view];
    _texetView.backgroundColor =  [UIColor whiteColor];
    _texetView.layer.borderWidth = 0.5;
    _texetView.layer.borderColor = RGBA(225, 225, 225, 1).CGColor;
    _texetView.layer.masksToBounds = YES;
    
    [self Linview:CGRectMake(13, H(_texetView)/3, SCREEN_WIDTH-30, 0.5) BackgroundColor:RGBA(225, 225, 225, 1) AddView:_texetView];
    [self Linview:CGRectMake(13, H(_texetView)/3*2, SCREEN_WIDTH-30, 0.5) BackgroundColor:RGBA(225, 225, 225, 1) AddView:_texetView];
    [self Linview:CGRectMake(13, H(_texetView)/3*3, SCREEN_WIDTH-30, 0.5) BackgroundColor:RGBA(225, 225, 225, 1) AddView:_texetView];


    UILabel *label =[self CreatLabelWhithRect:CGRectMake(10, 4, 35,  H(_texetView)/3-5) Text:@"+86" TextColor:[UIColor blackColor] Font:0.05 AddView:_texetView];
    label.textAlignment = NSTextAlignmentCenter;
    
    /*获取验证码Bnt*/
    _taseBnt = [self CreatBntAddView:_texetView WhithRect:CGRectMake(Width(_texetView)-70-10, 10, 70, H(_texetView)/3-20) AndType:UIButtonTypeSystem AndBntImgName:@"yugv" AndTitle:@"获取验证码" Font:12];
    [_taseBnt addTarget:self action:@selector(getVerification) forControlEvents:UIControlEventTouchUpInside];
    [_taseBnt setTitleColor:mainColor forState:UIControlStateNormal];
    _taseBnt.layer.borderWidth = 1;
    _taseBnt.layer.borderColor =mainColor.CGColor;
    radius(_taseBnt, 3);
    
    _timeLab = [[UILabel alloc]initWithFrame:_taseBnt.frame];
    _timeLab.textColor = mainColor;
    _timeLab.textAlignment = NSTextAlignmentCenter;
    _timeLab.font = font(12);
    _timeLab.layer.borderColor = mainColor.CGColor;
    _timeLab.layer.borderWidth = 1;
    radius(_timeLab, 3);
    _timeLab.alpha = 0;
    [_texetView addSubview:_timeLab];
    
    //手机号text
    _phoneNub= [self CrectTextFieldWhithRect:CGRectMake(Width(label), 4, W(_texetView)-W(label)-W(_taseBnt)-25, H(_texetView)/3-5) Placeholder: @"手机号" FatherView:_texetView];
    _phoneNub.keyboardType = UIKeyboardTypeNumberPad;
    
    //验证码输入框
    _testText = [self CrectTextFieldWhithRect:CGRectMake(15, Height(_phoneNub)+4, SCREEN_WIDTH-30,H(_phoneNub)) Placeholder:@"请输入验证码" FatherView:_texetView];
    _testText.keyboardType = UIKeyboardTypeNumberPad;
    
    //密码输入框
    _passText =[self CrectTextFieldWhithRect:CGRectMake(X(_testText), Height(_testText)+4, W(_testText), H(_phoneNub)) Placeholder:@"请输入6-18位字母数字组合密码" FatherView:_texetView];
}
#pragma mark----发送短信验证码
-(void)getVerification{
    //判断手机号码是否符合规则
  NSString  *rule = @"^0{0,1}(13[0-9]|15[3-9]|15[0-2]|18[0-9]|17[5-8]|145|147|170)[0-9]{8}$";
    NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",rule];
    BOOL isMatch = [pred evaluateWithObject:_phoneNub.text];
    if (!isMatch)
    {
    [self ShowAlertWhthTitle:@"提示" Message:@"手机号码不合法请重新填写"  CancelButtonTitle:@"好"];
        return;
    }

    //手机号合法  发送验证码请求
    NSString *message= [NSString stringWithFormat:@"我们将发送验证码短信到这个号码:+86 %@",_phoneNub.text];
    UIAlertController *alert = [self ShowAlertWhthTitle:@"提示" Message:message CancelButtonTitle:@"取消"];
    
    //发送短信验证
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 
        [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
            self.formhash= responseObject[@"data"][@"formhash"];
            
//            NSLog(@"短信验证：：：%@",self.formhash);
            
            NSDictionary *dic = @{ @"mobile":_phoneNub.text,
                                   @"formhash":self.formhash,@"type":@"register"};
            [self getSMSWhithdic:dic];//发短信验证 请求  要先获取 formhash
            
        }];
        
    }];
    
    [alert addAction:cancel];
}
#pragma mark--获取fromhash后 发送短信验证请求
-(void)getSMSWhithdic:(NSDictionary *)dic{

            [[Manager sharedManager]ResponseWhithURL:SMSUrl AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
                
                NSLog(@"%@",responseObject);

                    if ([responseObject[@"code"] isEqualToString:@"200"]) {
                        
                        _timeLab.text = @"60S";
                        _taseBnt.alpha = 0;
                        _timeLab.alpha = 1;
                        count = 0;
                        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
                    }else{
                    
                    [self ShowAlertWhthTitle:@"发送失败" Message:@"请重新获取验证码" CancelButtonTitle:@"好"];
                }
            }];
}
-(void)updateTime
{
    count++;
    if (count >= 60)
    {
        //停止定时器
        [_timer invalidate];
        
        _timeLab.alpha = 0;
        _taseBnt.alpha = 1;
        return;
    }

    _timeLab.text = [NSString stringWithFormat:@"%iS",60-count];
}

-(void)FootView{
    UIButton *bnt = [self CreatBntAddView:self.view WhithRect:CGRectMake(15, Height(_texetView)+15, 20, 20) AndType:UIButtonTypeCustom AndBntImgName:@"empty" AndTitle:@"" Font:0];
    [bnt setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
    [bnt addTarget:self action:@selector(MyRead:) forControlEvents:UIControlEventTouchUpInside];
    radius(bnt, 3);

    UILabel *text = [self CreatLabelWhithRect:CGRectMake(Width(bnt)+5, Y(bnt), SCREEN_WIDTH*0.48, H(bnt)) Text:@"我已看过并同意钓鱼人必备" TextColor:RGBA(159, 159, 159, 1) Font:0.04 AddView:self.view];
    
    UIButton *pocolBnt = [self CreatBntAddView:self.view WhithRect:CGRectMake(Width(text), Y(text),SCREEN_WIDTH*0.35, H(text)) AndType:UIButtonTypeSystem AndBntImgName:@"haik" AndTitle:@"《用户使用协议》" Font:SCREEN_WIDTH*0.04];
    pocolBnt.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [pocolBnt setTitleColor:mainColor forState:UIControlStateNormal];
    [pocolBnt addTarget:self action:@selector(pushUserAgreement) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *nextBnt = [self CreatBntAddView:self.view WhithRect:CGRectMake(X(bnt),Height(bnt)+15, SCREEN_WIDTH-X(bnt)*2, 40) AndType:UIButtonTypeSystem AndBntImgName:@"aiksdn," AndTitle:@"下一步" Font:SCREEN_WIDTH*0.07];
    radius(nextBnt, 3);
    nextBnt.backgroundColor = mainColor;
    [nextBnt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextBnt addTarget:self action:@selector(nextCtl) forControlEvents:UIControlEventTouchUpInside];
}
-(void)MyRead:(UIButton *)read{

    read.selected = !read.selected;
    isRead = !isRead;
}
#pragma mark--验证手机验证码 并到下一个页面
-(void)nextCtl{
  
    if (_passText.text.length==0||_phoneNub.text.length!=11||_testText.text.length==0) {
        [Manager GetHudWhithText:@"请正确填写信息" AndFatherView:self.view];
    }else if (!isRead){
    
    
    }else{
    
        [self Submit];
    }
    
}
-(void)Submit{

    if(_testText.text.length != 4){
    [self ShowAlertWhthTitle:@"提示" Message:@"验证码格式错误,请重新填写" CancelButtonTitle:@"确定"];
    
    }else{
        
        
        NSDictionary *dic = @{@"mobile":_phoneNub.text,
                              @"sms_code":_testText.text,
                              };
        [[Manager sharedManager]ResponseWhithURL:SMSverify AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
            
            if ([responseObject[@"status"]isEqualToString:@"SUCCESS"]) {
                OkRegister *okregist = [OkRegister new];
                okregist.phoneNumb = _phoneNub.text;
                okregist.passWord =_passText.text;
                okregist.testText = _testText.text;
                [self.navigationController pushViewController:okregist animated:YES];
            }else{
                
                [Manager GetHudWhithText:responseObject[@"message"] AndFatherView:self.view];
                
            }
        }];

   }
}

-(UITextField *)CrectTextFieldWhithRect:(CGRect )rect Placeholder:(NSString *)string FatherView:(UIView *)fatherView{
    UITextField *textfiled = [[UITextField alloc]initWithFrame:rect];
    textfiled.placeholder = string;
    textfiled.clearButtonMode = UITextFieldViewModeAlways;
    textfiled.font = font(SCREEN_WIDTH*0.05);
    [fatherView addSubview:textfiled];

    return textfiled;
}

#pragma mark --- 跳转至HTML界面
- (void)pushUserAgreement{

    KGUserAgreementController *userAgree = [[KGUserAgreementController alloc] init];
    [self.navigationController pushViewController:userAgree animated:YES];
}

@end
